import { useState, useRef, useEffect } from "react";
import { Button, message, Space } from "antd";
import moment from "moment";
import { PlusOutlined, EditTwoTone } from "@ant-design/icons";
import ProTable from "@ant-design/pro-table";
import { ModalForm } from "@ant-design/pro-form";
import { addArgument } from "@/const";
import { useLocation, useHistory } from "umi";

import useCommonColumns from "./useCommonColumns";
import useRemove from "./useRemove";
export default ({
  initialValues = {},
  actionRef,
  columns, // 表格columns
  hiddenAction = false, // true = 隐藏操作列
  onlyColumns = false, // true = 只取自己传入的columns 不会追加默认项
  title, // 表格标题
  customTitle = "",
  onlyTitle = false, // true = 只取自己传入的title
  showCheckbox = true, // 是否可以进行多选操作
  onAdd, // 添加按钮触发
  onEdit, // 编辑按钮触发
  renderFormItem = () => {}, // 新增/编辑表单内容
  params = {}, // 请求分页列表额外参数
  fetchList,
  dataSource = null,
  add,
  update,
  remove,
  updateStatus,
  renderAdd, // 自定义添加按钮
  renderEdit, // 自定义编辑按钮
  renderAction, // 自定义操作
  insertPosition,
  renderOtherAction,
  actionColumnWidth, // 操作列宽度
  search = true, // 是否可以搜索
  scroll = false, // 是否开启超长表格滚动
  modalWidth = 1200, // 新增/编辑 弹框宽度
  onlyAction = false, // true = 分页列表只追加操作列（不追加【登记人，登记时间，状态】）
  pagination = true, // 是否显示分页
  onFinish = false, // 自定义提交表单方法
  addOtherParams = {},
  renderShowEdit = () => {
    return true;
  },
  renderShowRemove = () => {
    return true;
  },
  layout,
  toolBarRender,
  syncToUrl = false, // 是否同步查询参数到URL
}) => {
  const actionRefSelf = actionRef ? actionRef : useRef();
  const formRef = useRef();
  const location = useLocation();
  const history = useHistory();

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);

  // 同步查询参数到URL
  const syncParamsToUrl = (params) => {
    if (!syncToUrl) return;
    
    const searchParams = new URLSearchParams(location.search);
    
    // 更新查询参数
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
        searchParams.set(key, String(params[key]));
      } else {
        searchParams.delete(key);
      }
    });

    // 更新URL
    const newSearch = searchParams.toString();
    const pathname = location.pathname;
    history.replace(`${pathname}${newSearch ? '?' + newSearch : ''}`);
  };

  // 从URL解析查询参数
  const parseParamsFromUrl = () => {
    if (!syncToUrl) return {};
    
    const searchParams = new URLSearchParams(location.search);
    const urlParams = {};
    
    searchParams.forEach((value, key) => {
      // 处理数字类型
      if (!isNaN(value)) {
        urlParams[key] = Number(value);
      } else if (value === 'true') {
        urlParams[key] = true;
      } else if (value === 'false') {
        urlParams[key] = false;
      } else {
        urlParams[key] = value;
      }
    });
    
    return urlParams;
  };

  // 获取初始参数
  const getInitialParams = () => {
    const urlParams = parseParamsFromUrl();
    return { ...initialValues, ...urlParams };
  };

  const myToolBarRender = () => {
    const addArr = renderAdd
      ? [renderAdd(actionRefSelf)]
      : [renderModalForm(1)];
    if (toolBarRender) {
      addArr.push(toolBarRender(actionRefSelf));
    }
    return addArr;
  };

  // 新增和修改
  const renderModalForm = (type, record) => {
    console.log("record===", record);
    // type 1=新增 2=修改
    const modalTitle = customTitle || (type === 1 ? "新增" : "编辑") + title;

    const handleAddOrUpdate = async (fields) => {
      const postData = {
        ...fields,
        id: record?.id || record?._id,
        ...addOtherParams,
      };
      let func = add;
      if (type === 2) {
        func = update;
      }
      // console.log("postData===",postData); return;
      const res = await func(postData);
      if (res.code == 0) {
        message.success(modalTitle + "成功");
        if (type === 1) {
          formRef.current?.resetFields();
        }
        actionRefSelf?.current.reload();
        return true; // 关闭弹框
      }
    };

    return (
      <ModalForm
        key={"key" + record?._id}
        formRef={formRef}
        layout={layout || "vertical"} // horizontal inline
        title={modalTitle}
        width={modalWidth}
        trigger={
          type === 1 ? (
            <Button
              key="add"
              icon={<PlusOutlined />}
              type="primary"
              onClick={onAdd}
            >
              {customTitle || `新增${title}`}
            </Button>
          ) : (
            <EditTwoTone
              key="update"
              onClick={onEdit}
              style={{ fontSize: 22 }}
            />
            // <Button key="update" type="primary" onClick={onEdit}>
            //   编辑
            // </Button>
          )
        }
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            formRef.current?.resetFields();
          },
          onSubmit: () => {
            formRef.current?.submit();
          },
        }}
        onFinish={async (values) => {
          return onFinish
            ? await onFinish(values, actionRefSelf)
            : await handleAddOrUpdate(values);
        }}
        initialValues={
          type == 1
            ? {
                ...initialValues,
              }
            : {
                ...record,
                status: record?.status === false ? false : true,
              }
        }
      >
        {renderFormItem({
          type,
          record,
          formRef,
        })}
      </ModalForm>
    );
  };

  // 封装函数，添加额外参数

  const dataColumns = [...columns].map((item) => {
    item.render = addArgument(item.render, actionRefSelf); // 给columns的render方法添加actionRef参数，可以进行列表的刷新
    return item;
  });
  console.log("dataColumns===", dataColumns);
  if (!onlyColumns) {
    dataColumns.push(
      ...useCommonColumns({
        renderEdit,
        renderShowEdit,
        renderShowRemove,
        renderModalForm,
        updateStatus,
        remove,
        actionRef: actionRefSelf,
        renderAction,
        insertPosition,
        renderOtherAction,
        actionColumnWidth,
        scroll,
        onlyAction,
        hiddenAction,
      })
    );
  }

  const proTableBaseProps = {
    search,
    actionRef: actionRefSelf,
    rowKey: "id",
    columns: dataColumns,
    // toolbar: {
    //   title: title || null,
    // },
    toolBarRender: myToolBarRender,
    options: false,
    tableAlertRender: ({ selectedRowKeys, selectedRows, onCleanSelected }) => (
      <Space>
        <span>
          已选 <span className="red">{selectedRowKeys.length}</span> 条
        </span>
        {useRemove(remove, null, actionRefSelf, { ids: selectedRowKeys })}
      </Space>
    ),
    rowSelection: showCheckbox
      ? {
          selectedRowKeys,
          onChange: (newSelectedRowKeys, newSelectedRows) => {
            setSelectedRowKeys(newSelectedRowKeys);
            setSelectedRows(newSelectedRows);
          },
          // getCheckboxProps: (record) => ({
          //   disabled: record.status === 2,
          // }),
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
        }
      : false,
    scroll,
    pagination: pagination
      ? {
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          defaultPageSize: 100,
        }
      : false,
    // 同步参数到URL
    onSubmit: (params, form) => {
      if (syncToUrl) {
        syncParamsToUrl(params);
      }
      return true;
    },
    // 初始值从URL获取
    form: {
      initialValues: getInitialParams(),
    },
  };

  const proTableProps = dataSource
    ? { ...proTableBaseProps, dataSource }
    : {
        ...proTableBaseProps,
        request: fetchList
          ? async (innerParams) => {
              // 同步查询参数到URL
              if (syncToUrl) {
                syncParamsToUrl(innerParams);
              }
            
              const postData = { ...innerParams, ...params };
              if (postData.modidate) {
                postData.beginModidate = moment(postData.modidate[0]).format(
                  "YYYY-MM-DD HH:mm:ss"
                );
                postData.endModidate = moment(postData.modidate[1]).format(
                  "YYYY-MM-DD HH:mm:ss"
                );
              }
              postData.pageNum = postData.current;
              delete postData.current;
              delete postData.modidate;
              const res = await fetchList(postData);
              return {
                data: res?.rows || res?.data,
                total: res?.total,
                success: true,
              };
            }
          : null,
      };

  return (
    <>
      <ProTable {...proTableProps} />
    </>
  );
};
